<!-- 用户管理 -->
<template>
    <div class="user-box">
        <!-- 查询 -->
        <el-form :inline="true" ref="userRuleFormRef" :model="userRuleForm" label-width="120px" class="demo-ruleForm"
            :size="formSize" status-icon>
            <el-form-item label="用户ID" prop="userId">
                <el-input v-model.trim="userRuleForm.userId" placeholder="请选择用户ID" />
            </el-form-item>
            <el-form-item label="用户名称" prop="userName">
                <el-input v-model.trim="userRuleForm.userName" placeholder="请选择用户名称" />
            </el-form-item>
            <el-form-item label="在职状态" prop="state">
                <el-select v-model="userRuleForm.state" placeholder="请选择用户状态">
                    <el-option :label="itme.label" :value="itme.value" v-for="(itme, index) in options" :key="index" />
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="userSubmitForm(userRuleFormRef)">查询</el-button>
                <el-button @click="resetForm(userRuleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 主体 -->
        <div class="table-but mb-5 mt-5">
            <el-button type="primary" @click="userAdd">新增</el-button>
            <el-button type="danger" @click="userDelete" v-has="'user-deleteAll'">批量删除</el-button>
            <el-button type="success">导出数据</el-button>
        </div>
        <!-- 表格数据 -->
        <div class="table-box">
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <!-- 复选框 -->
                <el-table-column type="selection" width="55" />
                <!-- 表格标题 -->
                <el-table-column :label="item.label" :prop="item.property" :formatter="item.formatter"
                    v-for="(item, index) in columns" :key="index" />
                <el-table-column align="center" label="操作">
                    <template #default="scope">
                        <el-button size="small" @click="handleEdit(scope.row)" v-has="'dept-edit'">编辑</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)"
                            v-has="'user-delete'">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="flex justify-center items-center mt-5">
                <el-pagination v-model:currentPage="pager.currentPage" v-model:page-size="pager.pageSize"
                    :page-sizes="[1, 3, 5, 10]" :small="small" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="pager.total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
            <!-- 对话框 -->
            <el-dialog v-model="dialogVisible" :title="active == 'add' ? '新增用户' : '编辑用户'" width="50%" draggable
                @close="dialogClose">
                <div>

                    <el-form ref="DialogRuleFormRef" :model="DialogRuleForm" :rules="rules" label-width="80px"
                        class="demo-ruleForm" :size="formSize" status-icon>
                        <el-form-item label="用户" prop="userName">
                            <el-input v-model="DialogRuleForm.userName" placeholder="请输入您的用户名" />
                        </el-form-item>
                        <el-form-item label="邮箱" prop="userEmail">
                            <el-input v-model="DialogRuleForm.userEmail" placeholder="请输入您的邮箱" />
                        </el-form-item>
                        <el-form-item label="手机号" prop="mobile">
                            <el-input v-model="DialogRuleForm.mobile" placeholder="请输入您的手机号" />
                        </el-form-item>
                        <el-form-item label="岗位" prop="job">
                            <el-input v-model="DialogRuleForm.job" placeholder="请输入您的岗位" />
                        </el-form-item>

                        <el-form-item label="状态" prop="state">
                            <el-select v-model="DialogRuleForm.state" placeholder="请输入您的状态">
                                <el-option :label="item.label" :value="item.value" v-for="item, index in DialogOptions"
                                    :key="index" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="系统角色" prop="roleList">
                            <el-select v-model="DialogRuleForm.roleList" multiple placeholder="请选择角色"
                                style="width: 240px">
                                <el-option v-for="item in options1" :key="item._id" :label="item.roleName"
                                    :value="item._id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="部门" prop="deptId">
                            <el-cascader :options="options2" :props="props1" clearable placeholder="请选择部门"
                                v-model="DialogRuleForm.deptId" />
                        </el-form-item>


                    </el-form>

                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="DialogSubmitForm(DialogRuleFormRef)">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { validateMobile } from '../../utils/vaildate'
import api from '../../api'

onMounted(() => {
    getuserlistapi()
    getrolelistapi()
    getdeptlistapi()
})
//获取用户列表
const getuserlistapi = () => {
    api.getUserListApi({ ...userRuleForm, ...pager }).then((res: any) => {
        let { list, total } = res
        //处理一下时间格式
        list.forEach((item: any) => {
            item.createTime = item.createTime && changeTime(item.createTime)
            item.lastLoginTime = item.lastLoginTime && changeTime(item.lastLoginTime)
        })
        tableData.value = list//用户列表
        pager.total = total//总数据数量
    })
}
// 获取到对话框角色的数据
const getrolelistapi = (obj?: any) => {
    api.getRoleListApi({ ...obj, ...pager }).then((res: any) => {
        let { list } = res
        options1.value = list//角色列表
    })
}
//获取对话框部门列表
const getdeptlistapi = () => {
    api.getDeptListApi().then((res: any) => {
        options2.value = res
    })
}



// 处理时间函数
const changeTime = (tiem: any) => {
    // 创建一个Date对象
    let date = new Date(tiem); // 注意月份是从0开始的，所以5月是4
    // 获取年、月、日、时和分的值
    let year = date.getFullYear();
    let month = date.getMonth() + 1; // 月份加1，因为getMonth()返回的是0-11
    let day = date.getDate();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    // 格式化日期时间字符串
    let formattedDate = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) + ' ' + (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes);
    return formattedDate;
}


// 头部查询
const formSize = ref('default')//用于控制该表单内组件的尺寸
const userRuleFormRef = ref<FormInstance>()//获取ref节点
//查询的数据
const userRuleForm = reactive({
    userId: '',
    userName: '',
    state: 0
})
//是否在职状态列表
const options = ref([
    { label: '所有', value: 0 },
    { label: '在职', value: 1 },
    { label: '离职', value: 2 },
    { label: '试用期', value: 3 },
])
//查询按钮
const userSubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 调用全部用户列表接口
            getuserlistapi()
        } else {
            console.log('error submit!', fields)
        }
    })
}
//重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}





// 表格操作按钮(对话框)
const dialogVisible = ref(false)//对话框开关
const active = ref('add')//判断对话框是添加还是编辑
const DialogRuleFormRef = ref<FormInstance>()//获取ref节点
// 提交表单数据
const DialogRuleForm = reactive({
    userName: '',
    userEmail: '',
    mobile: '',
    job: '',
    state: 1,
    roleList: [],
    deptId: '',
})
// 对话框表单验证
const rules = reactive({
    userName: [
        {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
        },
        {
            min: 2,
            max: 10,
            message: '用户名长度在2-10之间',
            trigger: 'blur',
            informType: 'warning',
        },
    ],
    mobile: [
        {
            required: true,
            validator: validateMobile//自定义表单验证
        },
    ],
    state: [
        {
            required: true,
            message: '请选择状态',
            trigger: 'blur',
        },
    ],
})
//对话框里的状态列表
const DialogOptions = ref([
    { label: '在职', value: 1 },
    { label: '离职', value: 2 },
    { label: '试用期', value: 3 },
])
//多选系统角色对话框
// const value1 = ref([])
//系统角色列表
const options1: any = ref([])
// 多选部门(级联选择器)
const props1 = {
    checkStrictly: true,//设置父子节点取消选中关联，从而达到选择任意一级选项
    label: 'deptName',
    value: '_id'
}
// 多选部门(级联选择器)
const options2: any = ref([])
//确定按钮(新增/编辑)
const DialogSubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            let params: any = DialogRuleForm
            //判断是新增还是编辑
            params.active = active.value
            //调用新增/编辑用户接口
            api.getUserOperateApi(params).then(res => {
                if (res) {
                    //关闭对话框
                    dialogVisible.value = false
                    // 调用全部用户列表接口
                    getuserlistapi()
                }
            })
            console.log(params);

        } else {
            console.log('error submit!', fields)
        }
    })
}
//对话框关闭回调
const dialogClose = () => {
    //重置表单数据
    resetForm(DialogRuleFormRef.value)
}





//新增
const userAdd = () => {
    dialogVisible.value = true//开启对话框
    active.value = 'add'//新增状态
}
// 批量删除
const userDelete = () => {
    // 获取多选数据的userId数组
    let arr = multipleSelection.value.map(item => {
        return { userId: item.userId, state: item.state }
    })

    if (arr.length !== 0) {
        ElMessageBox.confirm(
            '您确定要批量删除这些数据吗?',
            '提示',
            {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'warning',
                draggable: true,//属性为true以做到拖拽
            }
        )
            .then(() => {
                // 调用删除数据接口
                api.getUserDeleteApi({ userDelList: arr }).then(res => {
                    if (res) {
                        // 调用全部用户列表接口
                        getuserlistapi()
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                    }
                })
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '已取消删除',
                })
            })
    } else {
        ElMessage({
            message: '请选择要批量删除的数据',
            type: 'warning',
        })
    }

}

// 主体表格
// 表单数据
const tableData: any = ref([])
// 表格标题
const columns = [
    {
        label: '用户ID',
        property: 'userId',
    },
    {
        label: '用户名',
        property: 'userName'
    },
    {
        label: '用户邮箱',
        property: 'userEmail'
    },
    {
        label: '用户角色',
        property: 'role',
        formatter: function (_row: any, _column: any, cellValue: string | number, _index: any) {
            let arr: any = ['管理员', '普通用户']
            return arr[cellValue]
        }
    },
    {
        label: '用户状态',
        property: 'state',
        formatter: function (_row: any, _column: any, cellValue: string | number, _index: any) {
            let obj: Itable = {
                0: '所有',
                1: '在职',
                2: '离职',
                3: '试用期'
            }
            return obj[cellValue]
        }
    },
    {
        label: '注册时间',
        property: 'createTime',
        // width: '210px',
    },
    {
        label: '用户最后登陆时间',
        property: 'lastLoginTime',
        // width: '210px',

    }
]
//已勾选的复选框数据
const multipleSelection = ref<User[]>([])
// 当选择项发生变化时会触发该事件(复选框改变触发)
const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
}
// 单个编辑
const handleEdit = (row: User) => {
    active.value = 'edit'//编辑状态
    nextTick(() => {    //nextTick:在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法，获取更新后的 DOM。(重置表单数据)
        Object.assign(DialogRuleForm, row)//将当前行的数据赋值给表单    Object.assign()合并/覆盖对象
    })
    dialogVisible.value = true//开启对话框
}
// 单个删除
const handleDelete = (row: User) => {
    let arr = [{ userId: row.userId, state: row.state }]
    ElMessageBox.confirm(
        '您确定要删除吗?',
        '提示',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
            draggable: true,//属性为true以做到拖拽
        }
    )
        .then(() => {
            // 调用删除数据接口
            api.getUserDeleteApi({ userDelList: arr }).then(res => {
                if (res) {
                    // 调用全部用户列表接口
                    getuserlistapi()
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            })
        })
}


//分页
const pager = reactive({
    currentPage: 1,//初始化为第1页
    pageSize: 10,//一页多少条数据
    total: 0,//总条数
})
const small = ref(false)//是否使用小型分页样式
const background = ref(false)//是否为分页按钮添加背景色
const disabled = ref(false)//是否禁用分页
//一页的条数改变时触发
const handleSizeChange = (val: number) => {
    pager.pageSize = val
    getuserlistapi()//调用用户列表接口
}
//当前页变动时候触发
const handleCurrentChange = (val: number) => {
    pager.currentPage = val
    getuserlistapi()//调用用户列表接口
}


</script>

<style scoped lang="less">
.el-select {
    width: 200px;
}

.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}
</style>